//////////////////////////////////////////////////////////////////////////////////
//	Copyright 2011 by Yosef Grabivker, ryuho@homenetworksoft.com
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.
//////////////////////////////////////////////////////////////////////////////////

#include <wx/wx.h>
#include <wx/thread.h>
#include <wx/process.h>
#include <wx/utils.h>
#include "locallink.h"

#ifdef LINUX
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>

void handleSIGCHLD(int nVal)
{
   int stat;

   /*Kills all the zombie processes*/
   while(waitpid(-1, &stat, WNOHANG) > 0);
}
#endif

CLocalLink::CLocalLink()
{
#ifdef LINUX
	signal(SIGCHLD, handleSIGCHLD);
#endif	
}

CLocalLink::~CLocalLink()
{
}

RTSTRING CLocalLink::ReadFile(const wxString& strPath)
{
	RTSTRING str;
	
#ifdef LINUX
	int fd[2];
	pid_t pid;
	char line[1000];
	char cmd[128];
	sprintf(cmd, "cat %s", (const char*)strPath.ToAscii());
	
	memset(line,0,sizeof(line));

	pipe(fd);
	
	pid = fork();
	
	/* parent */
	if (pid > 0)
	{
		wxThread::Sleep(100);
		close(fd[1]);
	    read(fd[0], line, sizeof(line));
	    close(fd[0]);
	    
	    str+=line;
	    
	}
	else
	{
		close(fd[0]);
		dup2(fd[1], STDOUT_FILENO);
		dup2(fd[1], STDERR_FILENO);
		close(fd[1]);
		execl("/bin/sh", "sh", "-c", cmd, (char *) 0);
	}
#endif	
		
	return str;
}